package com.homework.api_user.services.impl;

import com.homework.api_user.client.CodeFeignClient;
import com.homework.api_user.services.UserService;
import com.homework.dao.domain.Token;
import com.homework.dao.domain.User;
import com.homework.dao.mapper.TokenMapper;
import com.homework.dao.mapper.UserMapper;
import com.homework.util.ResultMsg;
import com.homework.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    protected UserMapper userMapper;

    @Autowired
    protected TokenMapper tokenMapper;

    @Autowired
    protected CodeFeignClient codeFeignClient;

    /**
     * 注册
     * @return
     */
    public ResultMsg register(String email, String passwd, String authCode) {
        //判断验证码是否正确
        if(isEmpty(email) || isEmpty(passwd) || isEmpty(authCode)) {
            return ResultUtil.error(1, "输入非法！");
        }

        ResultMsg validate = codeFeignClient.validate(email, authCode);
        if(validate.getCode() == 1) {
            return ResultUtil.error(2, "验证码错误！");
        }

        if(validate.getCode() == 2) {
            return ResultUtil.error(3, "验证码已过期！");
        }

        //判断是否已经注册
        if(isRegister(email)) {
            return ResultUtil.error(4, "邮箱已注册"); //已注册
        }

        //进行注册
        User user = new User();
        user.setEmail(email);
        user.setPassword(passwd);
        boolean b = userMapper.addUser(user);
        if(b == true) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(5, "服务错误");
        }
    }

    protected boolean isEmpty(String str) {
        if(str == null || str.length() == 0) {
            return true;
        }

        return false;
    }

    /**
     * 判断是否已经注册
     * @return
     */
    public boolean isRegister(String email) {
        User user = userMapper.selectByEmail(email);
        if(user != null) {
            return true;
        }

        return false;
    }

    /**
     * 登录
     * @return
     */
    public Token login(String email, String passwd) {
        User user = userMapper.selectByEmail(email);
        if(user == null) {
            return null;
        }

        if(!passwd.equals(user.getPassword())) {
            return null;
        }

        String uuid = UUID.randomUUID().toString();
        Token token = new Token();
        token.setEmail(email);
        token.setToken(uuid);

        boolean b = tokenMapper.updateToken(token);
        if(b == false) {
            return null;
        }

        return token;
    }

    public String getInfoByToken(String token) {
        Token token1 = tokenMapper.selectByToken(token);
        if(token1 != null) {
            return token1.getEmail();
        }

        return null;
    }
}
